package com.hmkj.admin.controller.investor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.entity.export.ExportUtils;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.Constants;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.investor.InvestorModel;
import com.hmkj.core.po.investor.Investor;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.investor.InvestorService;
import com.hmkj.core.service.system.AdminService;
import com.hmkj.core.service.user.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class InvestorJsonController extends GenericController {

    @Resource
    private InvestorService investorService;
    @Resource
    private UserService userService;
    @Resource
    private AdminService adminService;

    /**
     * 投资人列表json数据
     */
    @ResponseBody
    @RequestMapping(value = "/investor/json/list", method = RequestMethod.POST)
    @RequiresPermissions("sys:investor:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager, Constants.AG);
        return investorService.getDtGridList(dtgrid, InvestorModel.class);
    }

    /**
     * 添加
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/investor/json/add")
    @RequiresPermissions("sys:investor:add")
    public ResultEntity addJson(Investor model) throws Exception {
        if(null == model){
            throw new BussinessException("参数有误");
        }
        if(null == model.getUserId()){
            throw new BussinessException("请先选择用户");
        }
        if(StringUtils.isBlank(model.getAccountNo()) && StringUtils.isBlank(model.getAccountHomeNo())){
            throw new BussinessException("外盘账号或内盘账号必须填一个");
        }
        if(StringUtils.isNotBlank(model.getAccountNo())){
            if(model.getAccountNo().length()<4 || model.getAccountNo().length()>16){
                throw new BussinessException("外盘交易账号限制在4到16位");
            }else if(!ValidateUtils.isCharOrNumber(model.getAccountNo())){
                throw new BussinessException("外盘交易账号应为4到16位的字母或数字");
            }
            if(StringUtils.isBlank(model.getAccountPwd())){
                throw new BussinessException("请填写外盘交易密码");
            }else if(model.getAccountPwd().length()<6 || model.getAccountPwd().length()>20){
                throw new BussinessException("外盘交易密码限制在6到20位");
            }
        }
        if(StringUtils.isNotBlank(model.getAccountHomeNo())){
            if(model.getAccountHomeNo().length()<4 || model.getAccountHomeNo().length()>16){
                throw new BussinessException("内盘交易账号限制在4到16位");
            }else if(!ValidateUtils.isCharOrNumber(model.getAccountHomeNo())){
                throw new BussinessException("内盘交易账号应为4到16位的字母或数字");
            }
            if(StringUtils.isBlank(model.getAccountHomePwd())){
                throw new BussinessException("请填写内盘交易密码");
            }else if(model.getAccountHomePwd().length()<6 || model.getAccountHomePwd().length()>20){
                throw new BussinessException("内盘交易密码限制在6到20位");
            }
        }
        User user = userService.selectByPrimaryKey(model.getUserId());
        if(null == user){
            throw new BussinessException("指定用户不存在");
        }
        userService.updateByPrimaryKeySelective(new User(u->{
            u.setId(user.getId());
            u.setType(User.TYPE.T2.code);
        }));
        Investor investor1 = investorService.selectOne(new Investor(iv->{
            iv.setUserId(model.getUserId());
        }));
        if(null != investor1){
            throw new BussinessException("该用户已经被指定为投资人，请勿重复指定");
        }
        investorService.add(model);
        return ok();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping(value = "/investor/json/edit")
    @RequiresPermissions("sys:investor:edit")
    public ResultEntity edit(Investor model) throws Exception {
        //参数校验
        if(null == model || null == model.getId()){
            throw new BussinessException("参数有误");
        }
        if(StringUtils.isBlank(model.getAccountNo()) && StringUtils.isBlank(model.getAccountHomeNo())){
            throw new BussinessException("外盘账号或内盘账号必须填一个");
        }
        if(StringUtils.isNotBlank(model.getAccountNo())){
            if(model.getAccountNo().length()<4 || model.getAccountNo().length()>16){
                throw new BussinessException("外盘交易账号限制在4到16位");
            }else if(!ValidateUtils.isCharOrNumber(model.getAccountNo())){
                throw new BussinessException("外盘交易账号应为4到16位的字母或数字");
            }
            if(StringUtils.isBlank(model.getAccountPwd())){
                throw new BussinessException("请填写外盘交易密码");
            }else if(model.getAccountPwd().length()<6 || model.getAccountPwd().length()>20){
                throw new BussinessException("外盘交易密码限制在6到20位");
            }
        }else{
            model.setAccountPwd(null);
        }

        if(StringUtils.isNotBlank(model.getAccountHomeNo())){
            if(model.getAccountHomeNo().length()<4 || model.getAccountHomeNo().length()>16){
                throw new BussinessException("内盘交易账号限制在4到16位");
            }else if(!ValidateUtils.isCharOrNumber(model.getAccountHomeNo())){
                throw new BussinessException("内盘交易账号应为4到16位的字母或数字");
            }
            if(StringUtils.isBlank(model.getAccountHomePwd())){
                throw new BussinessException("请填写内盘交易密码");
            }else if(model.getAccountHomePwd().length()<6 || model.getAccountHomePwd().length()>20){
                throw new BussinessException("内盘交易密码限制在6到20位");
            }
        }else{
            model.setAccountHomePwd(null);
        }

        Investor investor = investorService.selectByPrimaryKey(model.getId());
        if(null == investor){
            throw new BussinessException("参数有误");
        }
        if(!model.getAccountNo().equals(investor.getAccountNo())){
            if(investorService.selectCount(new Investor(t->{
                t.setAccountNo(model.getAccountNo());
                t.setDelFlag(Investor.DELFLAG.NORMAL.code);
            }))>0){
                throw new BussinessException("该外盘交易账号已存在");
            }
        }
        if(!model.getAccountHomeNo().equals(investor.getAccountHomeNo())){
            if(investorService.selectCount(new Investor(t->{
                t.setAccountNo(model.getAccountHomeNo());
                t.setDelFlag(Investor.DELFLAG.NORMAL.code);
            }))>0){
                throw new BussinessException("该内盘交易账号已存在");
            }
        }
        investorService.updateByPrimaryKeySelective(new Investor(t->{
          t.setId(model.getId());
          t.setAccountNo(model.getAccountNo());
          t.setAccountPwd(model.getAccountPwd());
        }));
        return ok();
    }

    /**
     * 修改状态
     */
    @ResponseBody
    @RequestMapping(value = "/investor/json/state")
    @RequiresPermissions("sys:investor:state")
    public ResultEntity state(Integer id, Integer status) throws Exception {
        //参数校验
        if(null == id || null == status){
            throw new BussinessException("参数错误");
        }
        if(status != Investor.STATUS.T1.code && status != Investor.STATUS.T2.code){
            throw new BussinessException("状态参数错误");
        }
        Investor investor = investorService.selectOne(new Investor(c -> c.setId(id)));
        if(null ==investor){
            throw new BussinessException("该投资人不存在");
        }
        investor.setStatus(status);
        investorService.updateByIdAndVersionSelective(investor);
        return ok();
    }

    /**
     * 未绑定后台的投资人
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("investor/josn/bindList")
    public DtGrid bindListJson(String dtGridPager) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        DtGrid dtgrid = mapper.readValue(dtGridPager, DtGrid.class);
//        Map<String, Object> parameters = dtgrid.getFastQueryParameters();
//        List<Admin> admins =  adminService.select(new Admin(a->{
//            a.setType(Admin.TYPE.T2.code);
//            a.setDelFlag(Admin.DELFLAG.NORMAL.code);
//        }));
//        String userIds = "0";
//        if (admins != null && admins.size() > 0) {
//            userIds = admins.stream().map(param -> param.getBussId().toString()).collect(Collectors.joining(","));
//        }
//        parameters.put("nin_id",userIds);
//        dtgrid.setFastQueryParameters(parameters);
        dtgrid = investorService.getDtGridList(dtgrid, InvestorModel.class);
        return dtgrid;
    }

    /**
     * 列表导出
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "investor/json/export", method = RequestMethod.POST)
    public ResultEntity export(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        DtGrid dtgrid = dataAuthority(dtGridPager, Constants.AG);
        dtgrid  =  investorService.getDtGridListExport(dtgrid, InvestorModel.class);
        ExportUtils.export(request, response, dtgrid);
        return ok();
    }

}